var utils = (function(){
	var modalEventNames = ['show.bs.modal'/**展示触发*/,'shown.bs.modal'/**展示完触发*/,'hide.bs.modal'/**隐藏触发*/,'hidden.bs.modal'/**隐藏完触发*/];
	var setModalEvent = function($modal,events){
		if(!$modal||!$modal[0])return;
		$.each(modalEventNames,function(){
			$modal.off(this.toString());
		});
		$.each(events,function(eventName){
			modalEventNames.indexOf(eventName) && $modal.on(eventName,events[eventName]);
		});
	};
	var createModal = function(modalId,modalBody,modalTitle,modalFooter,events){
		var modalHtml = 
		 '<div id="'+modalId+'" class="modal fade" tabindex="-1" role="dialog" style="display: none;">'
		+'    <div class="modal-dialog">'
		+'        <div class="modal-content">'
		+'            <div class="modal-header">'
		+'               <button type="button" class="close" data-dismiss="modal" aria-label="Close">'
		+'          <span aria-hidden="true">×</span></button>'
		+'                <h4 class="modal-title">'+modalTitle+'</h4>'
		+'            </div>'
		+'            <div class="modal-body">'+modalBody+'</div>'
		+'            <div class="modal-footer">'+modalFooter+'</div>'
		+'        </div>'
		+'    </div>'
		+'</div>';
		$('#mainContent').append(modalHtml);
		var $modal = $('#'+modalId);
		setModalEvent($modal,events||{});
		return $modal;
	};
	var Alert = function(modalBody,modalTitle,closeEvent){
		var $alertModal = $('#alertModal');
		if(modalBody){
			modalTitle = modalTitle || '提示';
			var events = {};
			if(closeEvent)events[modalEventNames[3]] = closeEvent;
			if($alertModal[0]){
				$alertModal.find('.modal-title').html(modalTitle);
				$alertModal.find('.modal-body').html(modalBody);
				setModalEvent($alertModal,events);
			}else{
				$alertModal = createModal('alertModal',modalBody,modalTitle,'<button data-dismiss="modal" class="btn btn-primary">确定</button>',events);
			}
			$alertModal.modal();
		}else{
			$alertModal.modal('hide');
		}
	};
	var Confirm = function(modalBody,modalTitle,submitEvent,cancelEvent,closeEvent){
		var $confirmModal = $('#confirmModal');
		if(modalBody){
			modalTitle = modalTitle || '提示';
			var events = {};
			if(closeEvent)events[modalEventNames[3]] = closeEvent;
			if($confirmModal[0]){
				$confirmModal.find('.modal-title').html(modalTitle);
				$confirmModal.find('.modal-body').html(modalBody);
				setModalEvent($confirmModal,events);
			}else{
				$confirmModal = createModal('confirmModal',modalBody,modalTitle,'<button data-dismiss="modal" class="btn btn-default pull-left cancel">取消</button>&nbsp;<button class="btn btn-primary submit">确定</button>',events);
			}
			var $submitButton = $confirmModal.find('.submit');
			$submitButton.off('click');
			$submitButton.on('click',function(){
				submitEvent&&submitEvent();
				$confirmModal.modal('hide');
			});
			var $cancelButton = $confirmModal.find('.cancel');
			$cancelButton.off('click');
			cancelEvent&&$cancelButton.on('click',function(){
				cancelEvent();
			});
			$confirmModal.modal();
		}else{
			$confirmModal.modal('hide');
		}
	};
	var logout = function(){
		$.ajax({
			url:'${request.contextPath}/logout',
			dataType:'json',
			success:function(data){
				if(data.code==0){
					location.href="${request.contextPath}";
				}
			}
		});
	};
	var dataTables = function(t){
		t = t || {};
		if(!t.tableId||!t.url||!t.columns||t.columns.length<=0){
			Alert('dataTables方法缺少必要参数');
			return;
		}
		var dataTablesObj = $('#'+t.tableId).DataTable( {
	        "processing": true,//是否显示加载提示
	        "serverSide": true, //启用服务器端分页
	        "bFilter": false, //列筛序功能
	        "searching": false,//原生搜索
		    "ordering": false,//排序功能
	        "ajax": {
	            "url": t.url,
	            "type": t.type || "POST",
	            "data" : function ( d ) {
		        	var obj = {};
		        	obj['page'] = d.start/d.length+1;
		        	obj['rows'] = d.length;
		        	if(t.isSearch){
			        	$('.search-field').each(function(){
			        		if(this.value){
								var dataType = this.getAttribute('dataType');
								if(dataType == 'date'){
									obj[this.name] = new Date(this.value);
								}else{
									obj[this.name] = this.value;	        			
								}
			        		}
			        	});
		        	}
		        	if(t.data){
		        		var data = t.data;
		        		$.each(data,function(key){
		        			obj[key] = data[key];
		        		});
		        	}
	                return obj;
	            },
	            "dataSrc":function(result){
	            	var dataMap = {};
	            	$.each(result.data,function(){
	            		dataMap[this.id] = this;
	            	});
	            	dataTablesObj.result = result;
	            	dataTablesObj.dataMap = dataMap;
	            	return result.data;
	            }
	        },
	        "columns": function(){
	        	var columns_ = t.columns;
	        	var columns = [{
		            sTitle: '&nbsp;',
		            data: null,
		            className: 'text-center',
		            render:function(data,type,row,meta) {
		                return meta.row + 1 +
		                meta.settings._iDisplayStart;
		            }
		        }];
	        	var isDelete = t.isDelete || false;
	        	var isUpdate = t.isUpdate || false;
	        	$.each(columns_,function(i){
	        		var column = columns_[i];
	        		if(!column.isShow)return;
	        		var render = null;
	        		if(column.render){
	        			render = column.render
	        		}else if(column.dataSources){
	        			render = function(data,type,row,meta){
	        				var val = row[column.data];
	        				var target = column.dataSources.find(function(_this){
	        					if(val==_this.value)return _this;
	        				});
	        				return target?target.key:val;
	        			}
	        		}
	        		columns.push({"data":column.data,"visible":true,className: 'text-center',render:render});
	        	});
	        	if(t.isDelete || t.isUpdate){
	        		columns.push(
	        			{ "data": '操作' , "width":"14%", "ordering":false, "render": function ( data, type, row ) {
		                		return function(){
		                			var buttonHtml = [];
		                			t.isUpdate && buttonHtml.push('<button type="button" class="btn btn-info update" buttonUrl="'+t.updateUrl+'" rowId="'+row.id+'" ><i class="'+t.updateIcon+'"> 编辑</i></button> &nbsp;');
		                			t.isDelete && buttonHtml.push('<button type="button" class="btn btn-danger delete" rowId="'+row.id+'" buttonUrl="'+t.deleteUrl+'"><i class="'+t.deleteIcon+'"> 删除</i></button>');
		                			return buttonHtml.join('');
								};
		                	}
	        			}
	        		);
	        	}
	        	return columns;
	        }(),
	        "language" : { //国际语言转化
	        	"sProcessing" : "处理中...",
	        	"sLengthMenu" : "每页 _MENU_ 条记录",
	        	"sZeroRecords" : "没有匹配结果",
	        	"sInfo" : "第 _PAGE_ 页 ( 总共 _PAGES_ 页 ，总共_MAX_ 条记录)",
	        	"sInfoEmpty" : "无记录",
	        	"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
	        	"sInfoPostFix" : "",
	        	"sSearch" : "搜索:",
	        	"sUrl" : "",
	        	"sEmptyTable" : "表中数据为空",
	        	"sLoadingRecords" : "载入中...",
	        	"sInfoThousands" : ",",
	        	"oPaginate" : {
	        		"sFirst" : "首页",
	        		"sPrevious" : "上页",
	        		"sNext" : "下页",
	        		"sLast" : "末页"
	        	},
	        	"oAria" : {
	        		"sSortAscending" : ": 以升序排列此列",
	        		"sSortDescending" : ": 以降序排列此列"
	        	}
	        }
	    });
	    if(t.isSearch){
		    $('#'+t.tableId+'_search').on('click',function(){
		    	dataTablesObj.draw();
		    });
	    }
	    if(t.isAdd){
	    	var $addModal =$('#'+t.tableId+'_addModal');
		    $addModal.find('.save').on('click',function(){
		    	var requestParams = {};
		    	var isAjax = true;
		    	$addModal.find('.request-param').each(function(){
		    		var isNeed = this.getAttribute('isNeed');
		    		if(isNeed&&!this.value){
		    			Alert(isNeed);
		    			isAjax = false;
		    			return isAjax;
		    		}
		    		if(this.value)requestParams[this.name]=this.value;
		    	});
		    	if(isAjax){
			    	ajax({'url':t.addUrl,'data':requestParams,'sucfun':function(){
			    			if(t.addSucFun){
			    				t.addSucFun();
			    			}else{
				    			Alert('添加成功');
			    			}
			    			//表格刷新
			    			dataTablesObj.draw(false);
			    			$addModal.modal('hide');
			    		}
			    	});
		    	}
		    });
	    }
	    var $updateModal =$('#'+t.tableId+'_updateModal');
	    $('#'+t.tableId).on('click','button',function(){
	    	var $this = $(this);
	    	if($this.hasClass('update')&&t.isUpdate){
				if(!$updateModal[0])return;
				var currData = dataTablesObj.dataMap[$this.attr('rowId')];
				$.each(currData,function(i){
					if(!currData[i])return;
					var $find = $updateModal.find('[name='+i+']');
					if($find[0]){
						$find.val(currData[i]);
						$find.attr('lastValue',currData[i])
					}
				});
				$updateModal.modal();
	    	}else if($this.hasClass('delete')&&t.isDelete){
	    		Confirm('你确定删除该条数据吗?','删除提示',function(){
	    			ajax({'url':t.deleteUrl,'data':{id:$this.attr('rowId')},'sucfun':function(){
			    			if(t.deleteSucFun){
			    				t.deleteSucFun();
			    			}else{
			    				Alert('删除成功');
			    			}
			    			//表格刷新
			    			dataTablesObj.draw();
			    			$updateModal.modal('hide');
			    		}
			    	});
	    		});
	    	}
	    });
		if(t.isUpdate){
		    $updateModal.find('.save').on('click',function(){
		    	var requestParams = {};
		    	var isAjax = false;
		    	$updateModal.find('.request-param').each(function(){
		    		var isNeed = this.getAttribute('isNeed');
		    		if(isNeed&&!this.value){
		    			Alert(isNeed);
		    			return isAjax;
		    		}
		    		if(this.value){
		    			if(this.name=='id'){
		    				//这里主要是用来区分与else的差别，这里的判断不能去掉
		    			}else if(this.getAttribute('lastValue')!=this.value){
			    			isAjax = true;
		    			}else{
		    				return true;
		    			}
		    			requestParams[this.name]=this.value;
		    		}
		    	});
		    	if(isAjax){
		    		ajax({'url':t.updateUrl,'data':requestParams,'sucfun':function(){
			    			if(t.updateSucFun){
			    				t.updateSucFun();
			    			}else{
			    				Alert('更新成功');
			    			}
			    			//表格刷新
			    			dataTablesObj.draw(false);
			    			$updateModal.modal('hide');
			    		}
			    	});
		    	}
		    });
		}
	    return dataTablesObj;
	};
	/**
	 * conf = {
	 * 		type :默认post  
	 * 		url :请求url [必传]
	 * 		headers : Ajax请求中额外的HTTP信息头对象
	 * 		data:发送到服务器的数据；如果是GET请求，它会自动被作为参数拼接到url上。非String对象将通过 $.param 得到序列化字符串。
	 * 		dataType  :预期服务器返回的数据类型(“json”, “jsonp”, “xml”, “html”, or “text”) 默认json
	 * 		async  : (默认：false): 默认设置下，所有请求均为同步。如果需发送异步请求，请将此设置为 true。
	 * 		timeout  :以毫秒为单位的请求超时时间, 0 表示不超时。 
	 * 		beffun  :请求发出前调用,如果它返回 false ，请求将被取消。
	 * 		sucfun  :请求成功之后调用。传入返回后的数据，以及包含成功代码的字符串。
	 * 		errfun  :接口返回状态不等于0时调用，默认打印错误信息
	 * 		comfun  :请求完成时调用，无论请求失败或成功。
	 * }
	 */
	var ajax = function(conf){
		conf  = conf || {};
		$.ajax({
		    type: conf.type || 'POST' ,
		    url: conf.url,
		    headers: conf.headers || {},
		    data: conf.data || {},
		    dataType: conf.dataType || 'json',
		    async: conf.async || false,
		    timeout: conf.timeout || yAdmin.timeout,
		    beforeSend: function(){
		    	conf.beffun  && conf.beffun();
		    },
			success: function(data){
				if(data.code==0){
				    conf.sucfun && conf.sucfun(data);
				}else{
					conf.errfun?conf.errfun(data):Alert(data.msg);
				}
			},
			error: function(XMLHttpRequest, textStatus,errorThrown){
				console.log(XMLHttpRequest.status);
				console.log(XMLHttpRequest.readyState);
				console.log(textStatus);
				console.log(errorThrown);
				Alert('Ajax error!');
			},
			complete:function(){
				conf.comfun  && conf.comfun();
			}
		});
	};
	return {
		Alert:Alert,
		Confirm:Confirm,
		logout:logout,
		dataTables:dataTables,
		ajax:ajax
	}
}());